<template>
	<div class="app-container"  v-loading="loading" @contextmenu.prevent="">
		<div class="search-container  app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					<el-col :span="4">
						<el-tree-select  style="width: 100%;"
							placeholder="请选择所属公司" 
							v-model="queryParams.cid" 
							:data="baseConfigStore.newExCompanyList"
							:render-after-expand="false"
							 :default-expand-all="true" 
							 check-strictly clearable
							@node-click="nodeClickCompany" 
							@clear="nodeClearCompany">
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>
					</el-col>
					<el-col :span="3">
						<el-select v-model="queryParams.sid" placeholder="请选择仓库"
							clearable>
							<el-option v-for="item in stockList" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.name" placeholder="请输入仓位名称" clearable />
					</el-col>
					<el-col :span="6" >
						<el-button :loading="loading"  type="primary" @click="handleQuery">
							<template #icon><i-ep-search /></template>查询</el-button>
					</el-col>
				</el-row>
				<FilterColumn
				 class="filtBox"
				 @handleRefresh="resetQuery()"
				 :columns="false"></FilterColumn>
			</div>	
		</div>

		<el-card shadow="never">
			
			<div class="action-row">
				<el-button v-hasPerm="['wms.Position/save']"   @click="handleDo('','act_add')" type="primary" plain><template #icon><i-ep-plus /></template>新增</el-button>
				<el-button v-hasPerm="['wms.Position/update']"  @click="handleDo('', 'act_edit')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-edit/></template>修改</el-button>
				<el-button v-hasPerm="['PositionDelete']"  @click="handleDo('', 'act_del')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-delete/></template>删除</el-button>
			</div>
			
			

			<el-table  ref="dataTableRef" 
						v-loading="loading" 
						:data="tableData" 
						align="left"
						tooltip-effect="dark" 
						:show-overflow-tooltip="true"  border
						@cell-mouse-enter="rowMouse"
						@cell-mouse-leave="menuLineVisible=false"
						@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column type="index" label="序号" align="center" width="80" />
				<el-table-column label="所属公司" min-width="200" align="center" prop="company.name"></el-table-column>
				<el-table-column label="仓库名称" min-width="200" align="center" prop="stockroom.name">
					<template #default="scope">
						<span>{{ scope.row.stockroom.name }}</span>
					</template>
				</el-table-column>
				<el-table-column label="仓位位置" min-width="200" align="center" prop="name" />	
			</el-table>

			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" @pagination="handleQuery" />

		</el-card>

		<!-- 新增内容 -->
		<el-dialog v-model="dialogAdd.visible"
			 :close-on-click-modal="false"
			  :close-on-press-escape="false"
			class="elDiaLog" 
			lock-scroll 
			:title="dialogAdd.title" 
			width="1000" @close="handleCancle">
			<div v-loading="formloading">
				<FormCreate
				 :rule="dataRule?.rules" :option="options" v-model="formData" v-model:api="fApi">
				</FormCreate>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" v-no-more-click  @click="doData(dialogAdd.status)">
						{{['act_edit'].includes(dialogAdd.status)?'修改':'确定'}}</el-button>
					<el-button @click="handleCancle">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script setup lang="ts">
	defineOptions({
		name: "Stockroom",
		inheritAttrs: false,
	});
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	import formCreate from "@form-create/element-ui";
	//获取 formCreate 组件
	const FormCreate = formCreate.$form();
	//接口地址
	import {
		getPositionList,
		getPositionCreate,
		useRequestAny,
		getPositionEdit,
		getPositionDel,
		getStockroomSelectList
	} from "@/api/wms";

	//m默认搜索字段
	const queryParamsData={
		page: 1,
		limit: 20,
		sid: "",
		name:""
	}
	//搜索-字段配置
	const queryParams = reactive(JSON.parse(JSON.stringify(queryParamsData)));
	const loading = ref(false);
	const formloading = ref(false);//表单加载
	const ids = ref<number[]>([]);
	const total = ref(0);
	const tableData = ref([]);// table表格数据
	const multipleSelection =ref<any>([]);
	const menuLineVisible =ref(true);
	const rowR = ref<any>({});

	const stockList = ref<any>();
	const dialogAdd = reactive<any>({
		title: "添加仓库", //弹窗标题
		visible: false,   //弹窗显示or隐藏
		status:"act_add", //弹窗状态类型  
		value:{}   		  //携带整条参数 row
	});
	const dataRule = ref<any>();
	const bindData = ref<any>()
	const fApi = ref<any>({});
	const formData = ref({});
	const options = ref({
		//表单提交事件
		submitBtn: false,
		resetBtn: false
	});
	
	// 行菜单事件
	function rowMouse(row:any) {
		menuLineVisible.value = true
		rowR.value = row
	}
	// 数据多选事件
	function handleSelectionChange(val:any) {
		multipleSelection.value = val
	}
	// 操作按钮样式
	function buttonType(val:number) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}
	// 操作
	 function handleDo(row:any, act:string) {
		 let uItem:any= {};
		dialogAdd.status = act
		switch (act) {
			case 'act_add':
				dialogAdd.visible = true;
				dialogAdd.title = '添加仓位';
				dataRule.value =JSON.parse(JSON.stringify(bindData.value));
				break
			case 'act_edit':
				dialogAdd.visible = true;
				dialogAdd.title="编辑仓位"
				formloading.value = true;
				uItem =JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
				getPositionEdit({ id: uItem.id }).then((res) => {
					dataRule.value = res.data;
				}).finally(() => { 
					formloading.value =false
				})
				break
			case 'act_del':
				handleDelete(JSON.parse(JSON.stringify(row || multipleSelection.value[0])))
				break
			default:	
		}
	}
	// 提交数据
	function doData(act?:string) {
		fApi.value.validate((valid, fail) => {
			console.log(valid)
			if (valid === true) {
				formloading.value = true;
				var data = {
					url: dataRule.value.action,
					method: dataRule.value.method,
					data: formData.value
				}
				useRequestAny(data).then((res) => {
					ElMessage({
						message: res.msg,
						type: 'success',
					})
					formloading.value = false;
					handleQuery();
					handleCancle()
				}).finally(() => { })
			}
		})
	}
	function handleDelete(Id ?: number) {
		const Ids = [Id || ids.value].join(",");
		if (!Ids) {
			ElMessage.warning("请勾选删除项");
			return;
		}
		ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			loading.value = true;
			getPositionDel({
				id: Ids
			}).then((res) => {
				console.log(res)
				ElMessage({
					message: '删除成功',
					type: 'success'
				})
				handleQuery();
			}).finally(() => {
				loading.value = false;
			})
		}, function () {
			console.log('取消删除')
		})
	}
	//获取仓库信息列表
	function handleQuery() {
		loading.value = true;
		getPositionList(queryParams).then((res) => {
			tableData.value = res.data.list;
			total.value = res.data.count;
		}).finally(() => {
			loading.value = false;
		})
	}
	// 重置表单内容
	function handleCancle() {
		dialogAdd.visible = false;
	}
	// 刷新页面
	function resetQuery(){
		handleQuery();
	}
	
	// 获取options 配置项
	function get_options() {
		initDataForm();
	}

	// 初始化表单初始项
	function initDataForm() {
		getPositionCreate({  }).then((res) => {
			bindData.value = res.data;
			dataRule.value = res.data;
		}).finally(() => {})
	}
	
	
	// 选择公司id
	function nodeClickCompany(a : any, b : any, c : any, d : any) {
		queryParams.sid = "";
		initStockList(a.cid)
	}
	// 取消选择公司id
	function nodeClearCompany() {
		stockList.value = [];
		queryParams.sid = "";
	}
	/**获取仓库列表 */
	function initStockList(cid ?: number) {
		getStockroomSelectList({ cid: cid }).then((res) => {
			stockList.value = res.data;
		}).finally(() => { })
	}
	
	
	onMounted(() => {
		handleQuery();
		get_options();
	})
</script>

<style lang="scss" scoped>

</style>